import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import Mgr from './SecurityService'
import store from '../store/index'
const service = axios.create({})

function setAxiosConfig() {
  service.defaults.baseURL = configUrl.apiUrl
  service.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
  service.defaults.withCredentials = true


  service.interceptors.request.use(
    async config => {
      
if(config.url == '/api-archive/studys/listpage')
{
  if(config?.params?.is_fuzzy == false)
  {
    config['headers']['QueryMode'] = 'imagecenter'
    // console.log('配置数据是啥哦',config);

  }
  //影像列表查询---影像中心
}
      // if(config.url === '/api/tenant/permissions') {
      //   config.baseURL = 'http://192.168.10.87:9021'
      // }
      if (store.getters.group === 'tenancy') {
        config['headers']['Group'] = 'tenancy'
        if (config.url === '/api-cloudpacs/Composite/Config/ObservationRoom') {
          // if(config.url === '/api-cloudpacs/Config/ObseRoom') {
          config.headers.SystemId = config.params.SystemId
        } else if (config.url === '/api-cloudpacs/Composite/Config/DataDicDefine') {
          // } else if(config.url === '/api-cloudpacs/Config/DicDefine') {
          config.headers.SystemId = config.params.SystemId
        } else if (config.url === '/api-archive/studys/match/ris') {
          // } else if (config.url === '/api-archivemanage/studys/match/ris') {
        } else {
          if (sessionStorage.getItem('lastname')) {
            config.headers.SystemId = sessionStorage.getItem('lastname')
          }
        }
      } else if (store.getters.group === 'dept') {
        config['headers']['Group'] = 'dept'
        config['headers']['systemid'] = store.getters.systemid
      } else if (store.getters.group === 'doct') {
        config['headers']['Group'] = 'doct'
        config['headers']['systemid'] = store.getters.systemid
        config['headers']['institutionId'] = store.getters.deptInstitutionId
      } else {
        if (sessionStorage.getItem('lastname')) {
          config.headers.SystemId = sessionStorage.getItem('lastname')
        }
      }

      if (config.method === 'get') {
      }
      if (sessionStorage.getItem('EWTenancyId')) {
        config.headers['ew-tenancy-id'] = sessionStorage.getItem('EWTenancyId')
      }
      if(config.headers['Content-Type']){
        
        axios.defaults.headers['Content-Type'] = config.headers['Content-Type']
      }else{
        axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
      }
      axios.defaults.withCredentials = true
      try {
        let user = JSON.parse(store.getters.loginInfo);
        if (!user) {
          const manager = new Mgr()
          user = await manager.getRole()
        }
        config.headers.common.Authorization = user.token_type + ' ' + user.access_token
        return Promise.resolve(config)
      }
      catch (error) {
        return Promise.reject(error)
      }
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    response => {
      const res = response.data
      if (response.config.url.slice(-5) === 'split' && res.code === -1) {
        store.dispatch('imgSplit/setCloseLoading')
      }
      if (res.code !== 0 && res.type !== 'image/jpeg' && res.type !== 'application/octet-stream') {
        if (res.code === 401 || res.code === 403) {
          Message({
            message: '没有该操作的权限',
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          // Message({
          //   message: res.msg || 'Error',
          //   type: 'error',
          //   duration: 5 * 1000
          // })
        }
        // return Promise.reject(new Error(res.msg || 'Error'))
      }
      return res
    },
    async error => {
      const status = error.response ? error.response.status : null
      if (status === 401) {
        const config = error.config
        if (!config.__isRetryRequest) {
          const manager = new Mgr()

          try {
            let user = JSON.parse(store.getters.loginInfo);
            if (!user) {
              user = await manager.getRole()
            }
            config.__isRetryRequest = true
            config.headers.common.Authorization = user.token_type + ' ' + user.access_token
            return service(config)
          }
          catch (error_1) {
            manager.signIn()
            return Promise.reject(error_1)
          }
        }
      } else if (status === 403) {
        Message({
          message: '没有该操作的权限',
          type: 'error',
          duration: 5 * 1000
        })
      }
      if (status === 500) {
        // alert('服务器异常')
        return Promise.reject(error)

      }

      if(axios.isCancel(error)){
        //取消请求不用报错
        return Promise.reject(error)

      }

      if (error !== 'Unauthorized' && status !== 404) {
        
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(error)
    }
  )
}

export const pretty = function(promise) {

  return promise.then(data => {
    return [data, null];
  }).catch(err => {
    return [null, err];

  });
}

export { setAxiosConfig }
export default service
